import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from "@nestjs/core";
import { Observable } from 'rxjs';
import { Request } from "express";

/* 实现接口操作权限校验 */

@Injectable()
export class PermissionGuard implements CanActivate {

  @Inject(Reflector)
  private reflector: Reflector;

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    if(!request.user) return true;
    // 从loginGuard处理过的请求体中获取到用户权限信息
    const permission = request.user.permissions;
    // 获取当前handle需要的权限
    const requirePermissions = this.reflector.getAllAndOverride("require-permission", [
      context.getClass(),
      context.getHandler()
    ]);

    if(!requirePermissions) return true;
    // 判断当前用户权限是否满足handle需要的权限
    requirePermissions.forEach((ele: any) => {
      const found = permission.find(item => item.code === ele);
      if(!found) {
        throw new UnauthorizedException("您没有访问该接口的权限");
      }
    });

    return true;
  }
}
